package com.sudo.service.admin.config;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class CronTaskRegistry implements DisposableBean {

    final private static Map<Runnable, SchedulingTask> schedulingTaskMap = new ConcurrentHashMap<>(16);

    @Resource
    private TaskScheduler taskScheduler;

    /**
     * 添加定时任务
     * @param task
     * @param cronExpression
     */
    public void addCronTask(Runnable task, String cronExpression) {
        CronTask cronTask = new CronTask(task,cronExpression);
        if (null != cronTask) {
            Runnable runnable = cronTask.getRunnable();
            if (schedulingTaskMap.containsKey(runnable)) {
                //说明要添加的定时任务已经存在
                // 先把已经存在的定时任务移除，然后再添加新的定时任务
                removeCronTask(runnable);
            }
            // 添加一个新的定时任务
            schedulingTaskMap.put(runnable, scheduledCronTask(cronTask));
        }
    }

    private SchedulingTask scheduledCronTask(CronTask cronTask) {
        SchedulingTask schedulingTask = new SchedulingTask();
        schedulingTask.future = taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return schedulingTask;
    }

    public void removeCronTask(Runnable runnable) {
        // 1.从Map集合中移除
        SchedulingTask task = schedulingTaskMap.remove(runnable);
        // 2.取消正在执行的定时任务
        if (null != task) {
            task.cancel();
        }
    }

    @Override
    public void destroy() throws Exception {
        //1.让所有定时任务停止执行
        schedulingTaskMap.forEach((runnable, schedulingTask) -> {
            schedulingTask.cancel();
        });
        //2.清空集合
        schedulingTaskMap.clear();
    }
}
